import {
  ValidationOptions, registerDecorator,ValidationArguments,
  ValidatorConstraintInterface} from 'class-validator';
import { User } from '../entity';
import {createConnection} from "typeorm";

export class UsernameExist implements ValidatorConstraintInterface{
  async validate(username: any, args: ValidationArguments) {
    const connection = createConnection();
    const photoRepository = (await connection).getRepository(User);
    console.log(username,'2')
    return await photoRepository.findOne({ username }).then(user => {
      if (user) { return false; }
      return true;
    });
  }
}

export function IfUsernameExist(validationOptions?: ValidationOptions) {
  console.log(1)
  return (object: object, propertyName: string) => {
    registerDecorator({
      target: object.constructor,
      propertyName,
      options: validationOptions,
      constraints: [],
      validator: UsernameExist,
    });
  };
}